﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxGridView;
using System.Configuration;

public partial class ContratacionListado : PageBase
{
    #region ContratacionListado
    private DataTable ContratacionListadoTable
    {
        get
        {
            DataTable objTable = null;
            if (Cache["ContratacionListadoTable.aspx" + Session.SessionID] != null)
                objTable = (DataTable)Cache["ContratacionListadoTable.aspx" + Session.SessionID];
            return objTable;
        }
        set
        {
            if (value != null)
            {
                Cache.Insert("ContratacionListadoTable.aspx" + Session.SessionID, value, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero);
            }
        }
    }
    #endregion

    #region StrCcoId
    public string StrCcoId
    {
        get
        {
            if (ViewState["StrCcoId"] != null)
                return ViewState["StrCcoId"].ToString();
            return "";
        }
        set { ViewState["StrCcoId"] = value; }
    }
    #endregion

    #region crearContextItems
    private void crearContextItems()
    {
        try
        {
            Context.Items["StrCcoId"] = StrCcoId;
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('" + ex.Message.ToString() + "');", true);
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDatosContratos();

        }
        else
        {
            if (ContratacionListadoTable != null)
            {
                ASPxGridViewContratosListado.DataSource = ContratacionListadoTable;
                ASPxGridViewContratosListado.DataBind();
            }
        }

        if (Usuario.PerfilActual == 64 || Usuario.PerfilActual == 103 || Usuario.PerfilActual == 68 || Usuario.PerfilActual == 22)
            btnConsultaRapida.Visible = true;
        else
            btnConsultaRapida.Visible = false;
    }

    private void BindDatosContratos()
    {
        try
        {
            Model.DataClassesContratosDataContext contexto = new Model.DataClassesContratosDataContext(ConfigurationManager.AppSettings["Conn"]);
            var datos = from a in contexto.CON_CONTRATISTAs
                        join b in contexto.BAS_ZONAS_GEOGRAFICAs on a.ZON_ID equals b.ZON_ID
                        join e in contexto.BAS_ZONAS_GEOGRAFICA1s on b.ZON_PADRE_ID equals e.ZON_ID
                        select new
                        {
                            a.CCO_ID,
                            a.CCO_IDENTIFICACION,
                            a.CCO_NOMBRE,
                            a.CCO_COREO_ELECTRONICO,
                            a.CCO_DIRECCION,
                            a.CCO_TELEFONO_CELULAR,
                            a.CCO_PROFESION,
                            Municipio = b.ZON_NOMBRE,
                            Departamento = e.ZON_NOMBRE
                        };

            if (datos == null) return;
            ASPxGridViewContratosListado.BeginUpdate();
            ASPxGridViewContratosListado.DataSource = datos;// objProductosComercialesRendimientosData.DefaultView;
            ASPxGridViewContratosListado.DataBind();
            ASPxGridViewContratosListado.EndUpdate();
            ContratacionListadoTable = GetDataView(ASPxGridViewContratosListado);
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
            //throw;
        }
    }

    #region GetDataView
    private DataTable GetDataView(ASPxGridView grid)
    {
        DataTable dt = new DataTable();
        foreach (GridViewColumn col in grid.VisibleColumns)
        {
            GridViewDataColumn dataColumn = col as GridViewDataColumn;
            if (dataColumn == null) continue;
            dt.Columns.Add(dataColumn.FieldName);
        }
        for (int i = 0; i < grid.VisibleRowCount; i++)
        {
            DataRow row = dt.Rows.Add();
            foreach (DataColumn col in dt.Columns)
                row[col.ColumnName] = grid.GetRowValues(i, col.ColumnName);
        }
        return dt;
    }
    #endregion

    protected void btnActualizar_Click(object sender, EventArgs e)
    {
        List<object> keyValues = ASPxGridViewContratosListado.GetSelectedFieldValues("CCO_ID");

        try
        {
            foreach (object key in keyValues)
            {
                if (keyValues.Count == 1)
                {
                    StrCcoId = key.ToString();
                    crearContextItems();
                    Server.Transfer("Contratacion.aspx?SSM_ID=21", true);
                }
                else
                    if (keyValues.Count > 1)
                        msgBox1.alert("Debe Seleccionar un solo Registro para Editar");
            }
            if (keyValues.Count == 0)
                msgBox1.alert("Debe Seleccionar al un Registro para Editar");


        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('" + ex.Message.ToString() + "');", true);
        }
    }

    protected void btnExportar_Click(object sender, EventArgs e)
    {
        gridExport.WriteXlsToResponse();
    }


    protected void btnNuevo_Click(object sender, EventArgs e)
    {
        Server.Transfer("Contratacion.aspx?SSM_ID=21", true);
    }

    protected void btnConsultaRapida_Click(object sender, EventArgs e)
    {
        ASPxGridViewContratos.Visible = true;
        btnContrato.Visible = true;
    }

    protected void btnContrato_Click(object sender, EventArgs e)
    {
        List<object> keyValues = ASPxGridViewContratos.GetSelectedFieldValues("CTT_ID");

        try
        {
            string a = "";
            string ei = "";
            string r = "";

            foreach (object key in keyValues)
            {

                if (keyValues.Count == 1)
                {
                    //Consulta el rubro
                    //Consulta el Contratatista y pasa los parametos a,e y r

                    Model.DataClassesContratosDataContext contexto = new Model.DataClassesContratosDataContext(ConfigurationManager.AppSettings["Conn"]);
                    var datos = from aj in contexto.CON_CONTRATACIONs
                                join b in contexto.CON_CONTRATACION_FIN_ACCION_EPEs on aj.CTT_ID equals b.CTT_ID
                                join c in contexto.FIN_ACCION_EPEs on b.FAE_ID equals c.FAE_ID
                                join d in contexto.SIG_ACCIONs on c.ACC_ID equals d.ACC_ID

                                where aj.CTT_ID == Convert.ToDecimal(key.ToString())

                                select new
                                {
                                    aj.CTT_ID,
                                    aj.CCO_ID,
                                    d.PLN_ID
                                };
                    foreach (var item in datos)
                    {
                        a = key.ToString();
                        ei = item.CCO_ID.ToString();
                        r = item.PLN_ID.ToString();
                    }


                    StrCcoId = key.ToString();
                    crearContextItems();
                    Server.Transfer("Contratacion.aspx?SSM_ID=21&r=" + r + "&a=" + a + "&e=" + ei, true);
                }
                else
                    if (keyValues.Count > 1)
                        msgBox1.alert("Debe Seleccionar un solo Registro para Editar");
            }
            if (keyValues.Count == 0)
                msgBox1.alert("Debe Seleccionar al un Registro para Editar");


        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "msg1_error", "alert('" + ex.Message.ToString() + "');", true);
        }
    }
}